#include <iostream>
using namespace std;

#include <pthread.h>
#include <unistd.h>
pthread_mutex_t g_mutex;
void painter(const char *str)
{   
    if(str == NULL)
    {
        return;
    }

    while(*str != '\0')
    {
        cout<<*str;
        fflush(stdout);
        sleep(1);
        str++;
    
    }

    return;
}
//线程函数1
void *threadFunc1(void *arg)
{   
    const char *str1 = "hello";
    pthread_mutex_lock(&g_mutex);
    painter(str1);
    pthread_mutex_unlock(&g_mutex);
    pthread_exit(NULL);
}

//线程函数2
void *threadFunc2(void *arg)
{
    const char *str1 = "world";
    pthread_mutex_lock(&g_mutex);
    painter(str1);
    pthread_mutex_unlock(&g_mutex);
    pthread_exit(NULL);
}

int main()
{   
    //初始化锁
    pthread_mutex_init(&g_mutex,NULL);
    // 创建线程1
    pthread_t threadId1;
    int ret = pthread_create(&threadId1,NULL,threadFunc1,NULL);
    if(ret != 0)
    {
        perror("thread create error:");
        _exit(-1);
    }
    //创建线程2
    pthread_t threadId2;
    ret = pthread_create(&threadId2,NULL,threadFunc2,NULL);
    if(ret != 0)
    {
        perror("thread create error:");
        _exit(-1);
    }
    // 回收线程资源
    pthread_join(threadId1,NULL);
    pthread_join(threadId2,NULL);

    printf("l am man thread!\n");

    //释放锁资源
    pthread_mutex_destroy(&g_mutex);
    return 0;
}

//运行的进程卡死了。
//1.内核态阻塞
//用户态阻塞（死循环 & 进程占用的CPU较高）